<script setup>
import roleApi from "@/api/role.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus, Delete, Edit, Search, Refresh, User, Key, Setting} from '@element-plus/icons-vue'
import permissionApi from "@/api/permission.js";
import hasBtnPermission from "@/utils/btnPermission.js";

//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const roleQuery = ref({
    name: '',
    page: 1,
    limit: 10
})
const dateTimeRange = ref([])

const loadData = () => {
    roleApi.list(roleQuery.value).then(result => {
        if (result.code == 0) {
            list.value = result.data.records
            total.value = result.data.total
        }
    })
}
loadData()

const onSearch = () => {
    roleQuery.value.page = 1
    loadData()
}

const reset = () => {
    roleQuery.value.name = ''
    dateTimeRange.value = []
}

//根据ID删除
const deleteById = (id) => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            roleApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
    console.log('多选', rows)
    ids.value = rows.map(row => row.id)
    console.log(ids.value)
}
const deleteAll = () => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            roleApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//添加、编辑
const dialogFormVisible = ref(false)
const role = ref({})
const showAddDialog = () => {
    role.value = {}
    dialogFormVisible.value = true
}

const showUpdateDialog = (id) => {
    dialogFormVisible.value = true
    role.value = {}
    roleApi.selectById(id).then(result => {
        if (result.code == 0) {
            role.value = result.data
        }
    })
}

const addOrUpdate = () => {
    if (role.value.id) {
        roleApi.update(role.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    } else {
        roleApi.add(role.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    }
}

//权限分配的树形结构
const dialogPermissionVisible = ref(false)
const treeData = ref([])
const treeRef = ref()
const defaultProps = ref({
    children: 'children',
    label: 'name'
})
const showAssignedPermissionDialog = (row) => {
    role.value = row;
    dialogPermissionVisible.value = true;
    treeData.value = [];
    roleApi.selectAssignedPermission(row.id).then((result) => {
        treeData.value = result.data.permissionVOList;
        let checkedLeafIdList = [];
        getCheckedLeafIdList(result.data.permissionVOList, result.data.assignedPermissionIdList, checkedLeafIdList);
        treeRef.value.setCheckedKeys(checkedLeafIdList);
    });
}

const getCheckedLeafIdList = (permissionVOList, assignedPermissionIdList, checkedLeafIdList) => {
    permissionVOList.forEach(permissionVO => {
        assignedPermissionIdList.forEach(id => {
            //这个角色下面的权限，而且是没有孩子的叶子节点
            if (permissionVO.id==id && permissionVO.children.length == 0) {
                checkedLeafIdList.push(id);
            } else if(permissionVO.id==id && permissionVO.children.length != 0) {
                getCheckedLeafIdList(permissionVO.children, assignedPermissionIdList, checkedLeafIdList);
            }
        })
    });
}

const assignPermission = () => {
    let checkedNodes = treeRef.value.getCheckedNodes(false, true);
    console.log(checkedNodes);
    let permissionIds = checkedNodes.map((node) => node.id);
    permissionIds = permissionIds.join(',');
    roleApi.assignPermission(role.value.id, permissionIds).then((result) => {
        if (result.code === 0) {
            ElMessage({message: result.msg, type: 'success',})
            dialogPermissionVisible.value = false;
        }
    });
}
</script>

<template>
    <el-card>
        <template #header>
            <div class="header">
                <el-button type="primary" :disabled="!hasBtnPermission('role:add')" @click="showAddDialog">添加</el-button>
                <el-button type="primary" :disabled="!hasBtnPermission('role:deleteAll')" @click="deleteAll">批量删除</el-button>
            </div>
        </template>

        <el-form :inline="true">
            <el-form-item label="角色名称">
                <el-input v-model="roleQuery.name" placeholder="请输入角色名称" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    clearable
                    v-model="dateTimeRange"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="danger" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="角色名称"/>
            <el-table-column prop="code" label="角色编码" show-overflow-tooltip/>
            <el-table-column prop="description" label="角色描述" show-overflow-tooltip/>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="250px" fixed="right" label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                    <el-button size="small" type="success" @click="showAssignedPermissionDialog(row)">权限</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="roleQuery.page"
            v-model:page-size="roleQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>

    <!-- 添加编辑弹出框 -->
    <el-dialog v-model="dialogFormVisible" :title="role.id ? '编辑角色' : '添加角色'" width="500" :lock-scroll="false">
        <el-form :model="role" label-width="80px">
            <el-form-item label="角色名称">
                <el-input v-model="role.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色编码">
                <el-input v-model="role.code" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input v-model="role.description" type="textarea" :rows="3" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 权限分配弹窗 -->
    <el-dialog title="分配权限" v-model="dialogPermissionVisible" width="600px" :lock-scroll="false">
        <el-form ref="form" :model="role" label-width="80px">
            <el-form-item label="角色名称">
                <el-input v-model="role.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="权限列表">
                <el-tree
                    ref="treeRef"
                    :data="treeData"
                    :props="defaultProps"
                    show-checkbox
                    node-key="id"
                    :check-strictly="true"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="assignPermission">保存</el-button>
                <el-button @click="dialogPermissionVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
</style>